package com.renwei.yunlong.activity.news;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.me.DisplayUserInfoActivity;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.GroupChatBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.event.ChatDeleteEvent;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ChatMemberRefreshEvent;
import com.renwei.yunlong.event.ChatNameRefreshEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.RoundView;
import com.renwei.yunlong.view.SimpleOptionView;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.GlideCircleTransform;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.model.Conversation;

public class ChatSettingActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.iv_group)
    ImageView ivGroup;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.ll_group_info)
    LinearLayout llGroupInfo;
    @Bind(R.id.rl_group_member)
    RelativeLayout rlGroupMember;
    @Bind(R.id.tv_jiesan)
    TextView tvJiesan;
    @Bind(R.id.tv_member_count)
    TextView tvMemberCount;
    @Bind(R.id.tv_edit)
    TextView tvEdit;
    @Bind(R.id.tv_member_title)
    TextView tvMemberTitle;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    private RecyAdapter adapter;
    private String mTargetId;
    private Conversation.ConversationType chatType;
    private List<Contact> mMemberlist;
    private String outSourceFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_chat_setting);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);

        mTargetId = getIntent().getStringExtra("mTargetId");
        outSourceFlag = getIntent().getStringExtra("outSourceFlag");
        chatType = (Conversation.ConversationType) getIntent().getSerializableExtra("chatType");
        initView();
        initData();
    }

    private void initView() {
        if (chatType == Conversation.ConversationType.PRIVATE) { // 单聊
            simpleTileView.setTitle("对话信息");
            Glide.with(mContext).load(RongUserInfoManager.getInstance().getUserInfo(mTargetId).getPortraitUri()).
                    error(R.mipmap.icon_header_default).transform(new GlideCircleTransform(mContext)).into(ivGroup);
            tvEdit.setVisibility(View.GONE);
            tvJiesan.setVisibility(View.GONE);
            tvMemberTitle.setText("对话成员");
            tvName.setText(RongUserInfoManager.getInstance().getUserInfo(mTargetId).getName());
            tvMemberCount.setText("2人");
        } else {
            simpleTileView.setTitle("群组信息");
            tvMemberTitle.setText("群成员");
            Glide.with(mContext).load(R.mipmap.icon_group_default).transform(new GlideCircleTransform(mContext)).into(ivGroup);
            tvEdit.setVisibility(View.VISIBLE);
            tvJiesan.setVisibility(View.VISIBLE);
        }
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, 9));
        adapter = new RecyAdapter(mContext);
        recyclerView.setAdapter(adapter);
        rlGroupMember.setOnClickListener(this);
        llGroupInfo.setOnClickListener(this);
        tvJiesan.setOnClickListener(this);
    }

    private void initData() {
        // 单聊
        if (chatType == Conversation.ConversationType.PRIVATE) {
            List<Contact> list = new ArrayList<>();
            Contact bean2 = new Contact();
            bean2.setAvatar(RongUserInfoManager.getInstance().getUserInfo(mTargetId).getPortraitUri().toString());
            Contact bean3 = new Contact();
            bean3.setMipmap(R.mipmap.icon_chat_add);
            list.add(bean2);
            list.add(bean3);
            adapter.setData(list);
            adapter.setOnItemClickLitener(singleChatListener);
        } else { //群聊
            ServiceRequestManager.getManager().getChatGroupMember(this, mTargetId, this);
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onNameRefreshEvent(ChatNameRefreshEvent event){
        tvName.setText(event.name);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onCloseEvent(ChatListCloseEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onMemberRefreshEvent(ChatMemberRefreshEvent event){
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1:
                GroupChatBean bean = new Gson().fromJson(result, GroupChatBean.class);
                if (bean.getMessage().getCode() == 200) {
                    mMemberlist = bean.getRows();
                    if (mMemberlist != null && mMemberlist.size() != 0) {
                        tvName.setText(mMemberlist.get(0).getGroupName() + "(" + mMemberlist.size() + ")");
                        tvMemberCount.setText(mMemberlist.size() + "人");

                        // 判断是否为群主
                        String empId = "";
                        if ("1".equals(companyType)) {
                            empId = ownerBean.getRows().getEmployeeId();
                        } else if ("2".equals(companyType)) {
                            empId = serviceLoginBean.getRows().getEmployeeId();
                        }
                        tvJiesan.setText("退出群组");
                        for (Contact contact : mMemberlist) {
                            if (empId.equals(contact.getEmployeeId()) && "1".equals(contact.getIsMainGroup())) {
                                tvJiesan.setText("解散群组");
                                break;
                            }
                        }
                        // 增加操作
                        Contact bean1 = new Contact();
                        bean1.setMipmap(R.mipmap.icon_chat_add);
                        adapter.setData(mMemberlist);
                        adapter.addLastData(bean1);
                        adapter.setOnItemClickLitener(groupChatListener);
                    }
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            case 2:  // 退出群组
                CommonBean commonBean = new Gson().fromJson(result, CommonBean.class);
                if (commonBean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("操作成功");
                    EventBus.getDefault().post(new ChatDeleteEvent());
                    finish();
                } else {
                    showCenterInfoMsg(commonBean.getMessage().getMessage());
                }
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_jiesan:
                String s = tvJiesan.getText().toString();
                if ("退出群组".equals(s)) {
                    quitGroup();
                } else if ("解散群组".equals(s)) {
                    deleteGroup();
                }
                break;
            case R.id.ll_group_info: //信息
                if (chatType == Conversation.ConversationType.PRIVATE) { // 单聊
                    DisplayUserInfoActivity.OpenActivity(this, mTargetId, outSourceFlag);
                } else if (chatType == Conversation.ConversationType.GROUP) {
                    if (mMemberlist != null && mMemberlist.size() != 0)
                        GroupNameSettingActivity.OpenActivity(this, mMemberlist.get(0).getGroupId(), mMemberlist.get(0).getGroupName());
                }
                break;
            case R.id.rl_group_member: //成员
                if (mMemberlist != null && mMemberlist.size() != 0)
                    GroupMemberActivity.OpenActivity(this, mMemberlist.get(0).getGroupId());
                break;
            default:
                break;
        }
    }

    private void quitGroup() {
        HashMap<String, String> map = new HashMap<>();
        map.put("groupId", mMemberlist.get(0).getGroupId());
        if ("1".equals(companyType)) {
            map.put("employeeId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().exitChatGroup(this, JsonMapUtil.mapToJson(map), this);
    }

    private void deleteGroup() {
        HashMap<String, String> map = new HashMap<>();
        map.put("groupId", mMemberlist.get(0).getGroupId());
        if ("1".equals(companyType)) {
            map.put("employeeId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("employeeId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().deleteChatGroup(this, JsonMapUtil.mapToJson(map), this);
    }

    // 单聊 点击事件
    BaseRecyclerViewAdapter.OnItemClickLitener singleChatListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            if (position == adapter.getData().size() - 1) { // 最后一个 增加人员 发起群聊
                Contact item = new Contact();
                item.setEmployeeId(mTargetId);
                item.setName(RongUserInfoManager.getInstance().getUserInfo(mTargetId).getName());
                String sourceFlag = "";
                if ("1".equals(companyType)){
                    if ("0".equals(outSourceFlag)){
                        sourceFlag = "0";
                    }else{
                        sourceFlag = "1";
                    }
                }else if ("2".equals(companyType)){
                    if ("0".equals(outSourceFlag)){
                        sourceFlag = "1";
                    }else{
                        sourceFlag = "0";
                    }
                }
                item.setSourceFlag(sourceFlag);
                AppHelper.setCheck(item);
                StartChatActivity.openActivity(mContext, "");
            }
        }
    };
    // 群聊 点击事件
    BaseRecyclerViewAdapter.OnItemClickLitener groupChatListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            if (mMemberlist != null && mMemberlist.size() != 0)
                GroupMemberActivity.OpenActivity(mContext, mMemberlist.get(0).getGroupId());
        }
    };

    /**
     *
     * @param context
     * @param conversationType
     * @param mTargetId
     * @param outSourceFlag  单聊需要  传递的公司标志
     */
    public static void OpenActivity(Context context, Conversation.ConversationType conversationType,
                                    String mTargetId,String outSourceFlag) {
        Intent intent = new Intent(context, ChatSettingActivity.class);
        intent.putExtra("mTargetId", mTargetId);
        intent.putExtra("chatType", conversationType);
        if(TextUtils.isEmpty(outSourceFlag)){
            outSourceFlag = "0";
        }
        intent.putExtra("outSourceFlag", outSourceFlag);
        context.startActivity(intent);
    }

    class RecyAdapter extends BaseRecyclerViewAdapter<Contact> {

        public RecyAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyHolder(inflater.inflate(R.layout.item_start_iv, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            Contact item = getItem(position);
            MyHolder viewHolder = (MyHolder) holder;
            if (chatType == Conversation.ConversationType.PRIVATE) { // 单聊
                if (!TextUtils.isEmpty(item.getAvatar())) {
                    Glide.with(mContext).load(item.getAvatar())
                            .placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(viewHolder.civ);
                } else {
                    Glide.with(mContext).load(item.getMipmap())
                            .placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(viewHolder.civ);
                }
            } else {
                if (!TextUtils.isEmpty(item.getAvatar())) {
                    Glide.with(mContext).load("1".equals(item.getSourceFlag()) ? Api.$().SERVICE_FILE_URL + item.getAvatar() : Api.$().OWNER_FILE_URL + item.getAvatar())
                            .placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(viewHolder.civ);
                } else if (item.getMipmap() != 0) {
                    Glide.with(mContext).load(item.getMipmap())
                            .placeholder(R.mipmap.icon_header_default).error(R.mipmap.icon_header_default).into(viewHolder.civ);
                } else {
                    Glide.with(mContext).load(R.mipmap.icon_header_default).into(viewHolder.civ);
                }
            }

            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnItemClickLitener.onItemClick(view, position);
                }
            });
        }

        class MyHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.civ)
            RoundView civ;

            public MyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}

